<?php
namespace app;
use libs\HttpRequest;
use libs\Redis;
class QueryPhone{
	const TAOBAO_API = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm';
    const CACHE_KEY = 'PHONE:INFO';

    public static function query($phone){
        $ret = [];
        if(self::verifyPhone($phone)){
            // $name = Redis::getRedis()->get('name');
            $redisKey = substr($phone, 0,7);
            $phoneInfo = Redis::getRedis()->hGet(self::CACHE_KEY,$redisKey);
            if($phoneInfo){
                $ret = json_decode($phoneInfo,true);
                $ret['msg'] = '由自己数据库查询';
            } else {
                $res = httpRequest::request(self::TAOBAO_API,['tel'=>$phone]);
                $res = iconv("gb2312", "utf-8//IGNORE",$res);//我的页面是utf-8，file_get_contents的页面是gb2312，输出时中文乱码。
                $data = self::formatData($res);
                if($data){
                    $json = json_encode($data);
                    Redis::getRedis()->hSet(self::CACHE_KEY,$redisKey,$json);
                    $data['msg'] = '由阿里巴巴提供数据';
                    $ret = $data;
                }                
            }
        }
        return $ret;
    }

    /*
     * 校验手机号码的合法性
     */
    public static function verifyPhone($phone=null){
    	$res = false;
    	if($phone){
    		if(preg_match('/^1[34578]{1}\d{9}/',$phone)){
    			$res = true;
    		}
    	}
    	return $res;
    }

    /**
    *   格式化数据
    */
    public static function formatData($data = null){
        $result = false;
        if($data){
            preg_match_all("/(\w+):'([^']+)/", $data, $result);
            $result = array_combine($result[1], $result[2]);
        }
        return $result;
    }
}